﻿using System.Xml.Serialization;
using System;
using static System.Net.Mime.MediaTypeNames;
using System.IO;

namespace XML配置文件
{
    internal class Program
    {

        public static string ConfigFile
        {
            get
            {
                // 获取程序的运行路径
                var text = Environment.CurrentDirectory;
                text = Path.GetFullPath(Path.Combine(text, ""));
                if (!Directory.Exists(text))
                {
                    Directory.CreateDirectory(text);
                }
                // 组合基目录和子目录或文件
                return Path.Combine(text, "config.xml");
            }
        }

        static void Main(string[] args)
        {

            if (!File.Exists(ConfigFile))
            {
                // 如果文件不存在，则创建它  
                using (FileStream fs = File.Create(ConfigFile))
                {
                    Console.WriteLine("文件已被创建。");
                }
            }
            else
            {
                // 创建XmlSerializer实例  
                XmlSerializer serializer = new XmlSerializer(typeof(List<Person>));
                // 从文件中反序列化对象  
                using (FileStream stream = new FileStream(ConfigFile, FileMode.Open))
                {
                    List<Person> persons = (List<Person>)serializer.Deserialize(stream);
                    persons.ForEach(e =>
                    {
                        Console.WriteLine($"Name: {e.Name}, Age: {e.Age}");
                    });
                }

                // 或者从XML字符串中反序列化对象  
                //string xml = "<Person><Name>Bob</Name><Age>25</Age></Person>";
                //using (StringReader reader = new StringReader(xml))
                //{
                //    Person deserializedPerson = (Person)serializer.Deserialize(reader);
                //    Console.WriteLine($"Name: {deserializedPerson.Name}, Age: {deserializedPerson.Age}");
                //}

                //List<Person> persons = new List<Person> {
                //    new Person{
                //        Name = "叶静",Age = 12
                //    },

                //    new Person{
                //        Name = "王小二",Age = 12
                //    },
                //    new Person{
                //        Name = "王小二",Age = 12
                //    },
                //    new Person{
                //        Name = "王小二",Age = 12
                //    },
                //};
                //var fileStream = new FileStream(ConfigFile, FileMode.Open );
                //serializer.Serialize(fileStream, persons);
                //fileStream.Close();
            }
        }
    }


    public class Person
    {
        private String name;
        private int age;

        public String Name { get => name; set => name = value; }
        public int Age {  get => age; set => age = value;}
    }

}
